<?php

App::import('Model', 'Property');

class UsersController extends AppController {
    var $name = 'Users';
    var $helpers = array('Html', 'Form');
    var $group = null;

function login() {
	if ($this->Session != null)
		$this->Session->destroy();  
	// if the form was submitted
	if(!empty($this->data)) {
		// find the user in the database
		$dbuser = $this->User->findByUsername($this->data['User']['username']);
		// if found and passwords match
		if(!empty($dbuser) && ($dbuser['User']['password'] == md5($this->data['User']['password']))) {
			// redirect the user
			$this->Session->setFlash('You have successfully logged in.');
		} else {
			$this->Session->setFlash('Either your username or password is incorrect.');
		}
	}
}


    function logout() {
        $this->Session->destroy();  
		$this->Session->setFlash('Good-Bye');
        $this->redirect($this->Auth->logout());
    }

function index() {
	$this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid user', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    function add() {
        if (!empty($this->data)) {
            $this->User->create();
            $this->data['User']['end_date'] = null;
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The user has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
            }

        }
        $groups = $this->User->Group->find('list');
        $people = $this->User->Person->find('list');
        $customers = $this->User->Customer->find('list');
        $this->set(compact('groups', 'people', 'customers'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid user', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The user has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
        $groups = $this->User->Group->find('list');
        $people = $this->User->Person->find('list');
        $customers = $this->User->Customer->find('list');
        $this->set(compact('groups', 'people', 'customers'));
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for user', true));
            $this->redirect(array('action'=>'index'));
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
        if (!empty($this->data)) {
            // ACA SETEO EL UPDATED_BY
            $this->data['User']['end_date'] = date('Y-m-d H:i:s');
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('User deleted', true));
            } else {
                $this->Session->setFlash(__('User was not deleted', true));
            }
        }
        $this->redirect(array('action' => 'index'));
    }

    function welcome() {
	   $this->group = $this->User->getGroup($this->Session->read('Auth'));
	   switch ($this->group)
	   {
			   case 'administrator':
					   $this->set('menu','menuadministration');
					   break;
			   case 'buildings':
					   $this->set('menu','menubuildings');
					   break;
			   case 'expenditures':
					   $this->set('menu','menuexpenditures');
					   break;
			   case 'charges':
					   $this->set('menu','menucharges');
					   break;
	   		  case 'builadmin':
					   $this->set('menu','menubuiladmin');
					   break;
	   }
	   $name_grupo = 'menu'.$this->group;
	   $name = $this->Session->read('Auth');
	   $this->set('user',$name);
	   $this->set('name',$name['User']['username']);
	   $this->Session->write('grupo',$name_grupo);
	   /*Guardo en la sesion los edificios que puede tener acceso*/
	   /*Habria que sacar este hardcode para llamar a una funcion*/
	   /*que lo traiga desde la BD*/
	   $this->set('menu',$name_grupo);
	//   $permit_build = array(1,2,3,4);
	   $permit_build =  $this->get_permit_build();
	   $this->Session->write('permit_build',$permit_build);
	   $property       = new Property;
	   $permit_property  = $this->get_property($permit_build, $property);
	   $this->Session->write('permit_property',$permit_property);
	}
		
	function get_permit_build()
	{
		$user = $this->Session->read('Auth');
		$id  = $user['User']['id'];
		$sql =" select         building.building_id
                from   users as user,
                       customers as customer,
                       buildings as building
                       where user.id = $id
                       and customer.customer_id = user.customer_id
                       and customer.customer_id = building.building_id
                       union
                       select building.building_id
                       from   users as user,
                              groups as grp,
                              buildings as building
                       where user.id = $id
                       and user.group_id = grp.id
                       and grp.id = 1 " ;
		$data = $this->User->query($sql);
		$ids = array();
		foreach($data as $key => $value)
		{
			$ids[] = $value[0]['building_id'];
		}
		return $ids;
	}

	function add_property($building_id,$property_id)
	{
		 $permit  = $this->Session->read('permit_property');	
		 $permit[]  = array('building_id' => $building_id, 'property_id' => $property_id);
		 $this->Session->write('permit_property',$permit);
	}

	function add_build($building_id)
	{
		 $permit  = $this->Session->read('permit_build');	
		 $permit[]  = $building_id;
	     $this->Session->write('permit_build',$permit);
	}

	function get_property($permit_build ,$property)
	{
		$data = null;
		foreach($permit_build as $value)
		{
			$data[$value]  = $property->findAllByBuildingId($value);
		}
		foreach ($data as $key => $key2)
		{
			foreach( $key2 as $key3 => $val){
				$new[]  = array('building_id' => $val["Property"]["building_id"] , 
					            'property_id' => $val["Property"]["property_id"]); 
			}
		}
		return $new;
	}

    function beforeFilter() {
        $this->Auth->authenticate = ClassRegistry::init('User');
        parent::beforeFilter();
        $this->Auth->allow('login','logout','welcome');
    }

    function build_acl() {
        if (!Configure::read('debug')) {
            return $this->_stop();
        }
        $log = array();

        $aco =& $this->Acl->Aco;
        $root = $aco->node('controllers');
        if (!$root) {
            $aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
            $root = $aco->save();
            $root['Aco']['id'] = $aco->id;
            $log[] = 'Created Aco node for controllers';
        } else {
            $root = $root[0];
        }

        App::import('Core', 'File');
        $Controllers = Configure::listObjects('controller');
        $appIndex = array_search('App', $Controllers);
        if ($appIndex !== false ) {
            unset($Controllers[$appIndex]);
        }
        $baseMethods = get_class_methods('Controller');
        $baseMethods[] = 'buildAcl';

        $Plugins = $this->_getPluginControllerNames();
        $Controllers = array_merge($Controllers, $Plugins);

        // look at each controller in app/controllers
        foreach ($Controllers as $ctrlName) {
            $methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));

            // Do all Plugins First
            if ($this->_isPlugin($ctrlName)){
                $pluginNode = $aco->node('controllers/'.$this->_getPluginName($ctrlName));
                if (!$pluginNode) {
                    $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginName($ctrlName)));
                    $pluginNode = $aco->save();
                    $pluginNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $this->_getPluginName($ctrlName) . ' Plugin';
                }
            }
            // find / make controller node
            $controllerNode = $aco->node('controllers/'.$ctrlName);
            if (!$controllerNode) {
                if ($this->_isPlugin($ctrlName)){
                    $pluginNode = $aco->node('controllers/' . $this->_getPluginName($ctrlName));
                    $aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginControllerName($ctrlName)));
                    $controllerNode = $aco->save();
                    $controllerNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $this->_getPluginControllerName($ctrlName) . ' ' . $this->_getPluginName($ctrlName) . ' Plugin Controller';
                } else {
                    $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName));
                    $controllerNode = $aco->save();
                    $controllerNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $ctrlName;
                }
            } else {
                $controllerNode = $controllerNode[0];
            }

            //clean the methods. to remove those in Controller and private actions.
            foreach ($methods as $k => $method) {
                if (strpos($method, '_', 0) === 0) {
                    unset($methods[$k]);
                    continue;
                }
                if (in_array($method, $baseMethods)) {
                    unset($methods[$k]);
                    continue;
                }
                $methodNode = $aco->node('controllers/'.$ctrlName.'/'.$method);
                if (!$methodNode) {
                    $aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method));
                    $methodNode = $aco->save();
                    $log[] = 'Created Aco node for '. $method;
                }
            }
        }
        if(count($log)>0) {
            debug($log);
        }
    }

    function _getClassMethods($ctrlName = null) {
        App::import('Controller', $ctrlName);
        if (strlen(strstr($ctrlName, '.')) > 0) {
            // plugin's controller
            $num = strpos($ctrlName, '.');
            $ctrlName = substr($ctrlName, $num+1);
        }
        $ctrlclass = $ctrlName . 'Controller';
        $methods = get_class_methods($ctrlclass);

        // Add scaffold defaults if scaffolds are being used
        $properties = get_class_vars($ctrlclass);
        if (array_key_exists('scaffold',$properties)) {
            if($properties['scaffold'] == 'admin') {
                $methods = array_merge($methods, array('admin_add', 'admin_edit', 'admin_index', 'admin_view', 'admin_delete'));
            } else {
                $methods = array_merge($methods, array('add', 'edit', 'index', 'view', 'delete'));
            }
        }
        return $methods;
    }

    function _isPlugin($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) > 1) {
            return true;
        } else {
            return false;
        }
    }

    function _getPluginControllerPath($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[0] . '.' . $arr[1];
        } else {
            return $arr[0];
        }
    }

    function _getPluginName($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[0];
        } else {
            return false;
        }
    }

    function _getPluginControllerName($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[1];
        } else {
            return false;
        }
    }

/**
 * Get the names of the plugin controllers ...
 *
 * This function will get an array of the plugin controller names, and
 * also makes sure the controllers are available for us to get the
 * method names by doing an App::import for each plugin controller.
 *
 * @return array of plugin names.
 *
 */
    function _getPluginControllerNames() {
        App::import('Core', 'File', 'Folder');
        $paths = Configure::getInstance();
        $folder =& new Folder();
        $folder->cd(APP . 'plugins');

        // Get the list of plugins
        $Plugins = $folder->read();
        $Plugins = $Plugins[0];
        $arr = array();

        // Loop through the plugins
        foreach($Plugins as $pluginName) {
            // Change directory to the plugin
            $didCD = $folder->cd(APP . 'plugins'. DS . $pluginName . DS . 'controllers');
            // Get a list of the files that have a file name that ends
            // with controller.php
            $files = $folder->findRecursive('.*_controller\.php');

            // Loop through the controllers we found in the plugins directory
            foreach($files as $fileName) {
                // Get the base file name
                $file = basename($fileName);

                // Get the controller name
                $file = Inflector::camelize(substr($file, 0, strlen($file)-strlen('_controller.php')));
                if (!preg_match('/^'. Inflector::humanize($pluginName). 'App/', $file)) {
                    if (!App::import('Controller', $pluginName.'.'.$file)) {
                        debug('Error importing '.$file.' for plugin '.$pluginName);
                    } else {
                        /// Now prepend the Plugin name ...
                        // This is required to allow us to fetch the method names.
                        $arr[] = Inflector::humanize($pluginName) . "/" . $file;
                    }
                }
            }
        }
        return $arr;
    }

    function initDB() {
        $group =& $this->User->Group;
        //Allow admins to everything
		$group->id = 1;
		$this->Acl->allow($group, 'controllers');
		$this->Acl->allow($group, 'Pages');
		$this->Acl->allow($group, 'People');
		$this->Acl->allow($group, 'Accounts');
		$this->Acl->allow($group, 'LookupValues');
		$this->Acl->allow($group, 'Territories');
		$this->Acl->allow($group, 'Properties');
		$this->Acl->allow($group, 'PaymentDues');
		$this->Acl->allow($group, 'PeriodicExpenditureTypes');
		$this->Acl->allow($group, 'ExpenditureDistributions');
		$this->Acl->allow($group, 'Buildings');
		$this->Acl->allow($group, 'PropertyTypes');
		$this->Acl->allow($group, 'RefinancingSystems');
		$this->Acl->allow($group, 'Addresses');
		$this->Acl->allow($group, 'ExpenditureTypes');
		$this->Acl->allow($group, 'Users'); 
		$this->Acl->allow($group, 'Customers'); 
		$this->Acl->allow($group, 'CouncilMembers'); 

        //allow managers to posts and widgets
        $group->id = 2;

 		$this->Acl->allow($group, 'controllers');
		$this->Acl->allow($group, 'Pages');
		$this->Acl->allow($group, 'People');
		$this->Acl->allow($group, 'Addresses');
		$this->Acl->deny($group, 'Buildings');
		$this->Acl->allow($group, 'Buildings/index');
		$this->Acl->allow($group, 'Buildings/view');
		$this->Acl->allow($group, 'PaymentDues');
		$this->Acl->allow($group, 'RefinancingSystems');
		$this->Acl->allow($group, 'PropertyTypes');
		$this->Acl->allow($group, 'Accounts');
		$this->Acl->allow($group, 'Properties');
		$this->Acl->deny($group, 'Expenditures');
		$this->Acl->allow($group, 'Expenditures/index');
		$this->Acl->allow($group, 'Expenditures/consolidate');
		$this->Acl->allow($group, 'Expenditures/view');
		$this->Acl->deny($group, 'ExpenditureDistributions');
		$this->Acl->allow($group, 'ExpenditureDistributions/index');
		$this->Acl->allow($group, 'ExpenditureDistributions/view');
		$this->Acl->deny($group, 'ExpenditureTypes');
		$this->Acl->allow($group, 'ExpenditureTypes/index');
		$this->Acl->allow($group, 'ExpenditureTypes/view');
		$this->Acl->deny($group, 'PeriodicExpenditureTypes');
		$this->Acl->allow($group, 'PeriodicExpenditureTypes/index');
		$this->Acl->allow($group, 'PeriodicExpenditureTypes/view');
		$this->Acl->deny($group, 'Groups');
		$this->Acl->deny($group, 'Users');
		$this->Acl->deny($group, 'Territories');
		$this->Acl->deny($group, 'LookupValues');
		$this->Acl->deny($group, 'Customers'); 
		$this->Acl->allow($group, 'CouncilMembers'); 

		$group->id = 3;

		$this->Acl->allow($group, 'controllers');
		$this->Acl->allow($group, 'Pages');
		$this->Acl->allow($group, 'ExpenditureDistributions');
		$this->Acl->allow($group, 'Expenditures');
		$this->Acl->allow($group, 'PeriodicExpenditureTypes');
		$this->Acl->allow($group, 'ExpenditureTypes');
		$this->Acl->deny($group, 'People');
		$this->Acl->deny($group, 'LookupValues');
		$this->Acl->deny($group, 'Addresses');
		$this->Acl->deny($group, 'Buildings');
		$this->Acl->allow($group, 'Buildings/index');
		$this->Acl->allow($group, 'Buildings/view');
		$this->Acl->deny($group, 'RefinancingSystems');
		$this->Acl->deny($group, 'PaymentDues');
		$this->Acl->deny($group, 'PropertyTypes');
		$this->Acl->allow($group, 'PropertyTypes/index');
		$this->Acl->allow($group, 'PropertyTypes/view');
		$this->Acl->deny($group, 'Properties');
		$this->Acl->deny($group, 'Accounts');
		$this->Acl->deny($group, 'Groups');
		$this->Acl->deny($group, 'Users');
		$this->Acl->deny($group, 'Territories');
		$this->Acl->deny($group, 'Customers'); 
		$this->Acl->deny($group, 'CouncilMembers'); 

        $group->id = 4;
		
		$this->Acl->allow($group, 'controllers');
		$this->Acl->allow($group, 'Pages');
		$this->Acl->deny($group, 'ExpenditureDistributions');
		$this->Acl->deny($group, 'Expenditures');
		$this->Acl->allow($group, 'Expenditures/consolidate');                                                           
		$this->Acl->deny($group, 'PeriodicExpenditureTypes');
		$this->Acl->deny($group, 'ExpenditureTypes');
		$this->Acl->deny($group, 'People');
		$this->Acl->allow($group, 'People/index');
		$this->Acl->allow($group, 'People/view');
		$this->Acl->deny($group, 'LookupValues');
		$this->Acl->deny($group, 'Addresses');
		$this->Acl->deny($group, 'Buildings');
		$this->Acl->allow($group, 'Buildings/index');
		$this->Acl->allow($group, 'Buildings/view');
		$this->Acl->deny($group, 'RefinancingSystems');
		$this->Acl->allow($group, 'RefinancingSystems/index');
		$this->Acl->allow($group, 'RefinancingSystems/view');
		$this->Acl->deny($group, 'PaymentDues');
		$this->Acl->allow($group, 'PaymentDues/index');
		$this->Acl->allow($group, 'PaymentDues/view');
		$this->Acl->deny($group, 'PropertyTypes');
		$this->Acl->deny($group, 'Properties');
		$this->Acl->deny($group, 'Accounts');
		$this->Acl->deny($group, 'Groups');
		$this->Acl->deny($group, 'Users');
		$this->Acl->deny($group, 'Territories');
		$this->Acl->deny($group, 'Customers'); 
		$this->Acl->deny($group, 'CouncilMembers'); 

       //allow managers to posts and widgets
        $group->id = 5;

 		$this->Acl->allow($group, 'controllers');
		$this->Acl->allow($group, 'Pages');
		$this->Acl->allow($group, 'People');
		$this->Acl->allow($group, 'Addresses');
		$this->Acl->deny($group, 'Buildings');
		$this->Acl->allow($group, 'Buildings/index');
		$this->Acl->allow($group, 'Buildings/view');
		$this->Acl->allow($group, 'PaymentDues');
		$this->Acl->allow($group, 'RefinancingSystems');
		$this->Acl->allow($group, 'PropertyTypes');
		$this->Acl->allow($group, 'Accounts');
		$this->Acl->allow($group, 'Properties');
		$this->Acl->deny($group, 'Expenditures');
		$this->Acl->allow($group, 'Expenditures/index');
		$this->Acl->allow($group, 'Expenditures/consolidate');
		$this->Acl->allow($group, 'Expenditures/view');
		$this->Acl->deny($group, 'ExpenditureDistributions');
		$this->Acl->allow($group, 'ExpenditureDistributions/index');
		$this->Acl->allow($group, 'ExpenditureDistributions/view');
		$this->Acl->deny($group, 'ExpenditureTypes');
		$this->Acl->allow($group, 'ExpenditureTypes/index');
		$this->Acl->allow($group, 'ExpenditureTypes/view');
		$this->Acl->deny($group, 'PeriodicExpenditureTypes');
		$this->Acl->allow($group, 'PeriodicExpenditureTypes/index');
		$this->Acl->allow($group, 'PeriodicExpenditureTypes/view');
		$this->Acl->deny($group, 'Groups');
		$this->Acl->deny($group, 'Users');
		$this->Acl->deny($group, 'Territories');
		$this->Acl->deny($group, 'LookupValues');
		$this->Acl->deny($group, 'Customers'); 
		$this->Acl->allow($group, 'CouncilMembers'); 

        echo "all done";
        exit;
    }
}
?>
